<template>
	<div class="table-box">
		<ProTable
			ref="proTable"
			title="客户列表"
			:columns="columns"
			:requestApi="getTableList"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<!-- 表格 header 按钮 -->
			<template #tableHeader="scope">
				<el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增客户</el-button>
				<!-- <el-button type="primary" :icon="Upload" plain @click="batchAdd" v-auth="'batchAdd'">批量添加用户</el-button> -->
				<!-- <el-button type="primary" :icon="Download" plain @click="downloadFile" v-auth="'export'">导出用户数据</el-button> -->
				<!-- <el-button type="primary" plain @click="toDetail">To 子集详情页面</el-button> -->
				<el-button v-auth="'batchAdd'" type="danger" :icon="Delete" plain :disabled="!scope.isSelected"> 批量删除用户 </el-button>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>
			<!-- 表格操作 -->
			<template #operation="scope">
				<el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
				<el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
				<el-button type="primary" link :icon="Location" @click="openDialog(scope.row.id)">地址</el-button>
			</template>
		</ProTable>
		<UserDrawer ref="drawerRef" />
		<ImportExcel ref="dialogRef" />
		<Address v-model:showDialog="showDialog" :clientId="client_id"></Address>
	</div>
</template>

<script setup lang="tsx" name="customers">
import { ref, reactive } from "vue";
import { listClient, createClient, delClient, setClient } from "@/api/modules/connection";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/customers/components/UserDrawer.vue";
import Address from "@/views/customers/components/Address.vue";

import { CirclePlus, Delete, EditPen, Location } from "@element-plus/icons-vue";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	// type: 1
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
	return {
		list: data.data,
		total: data.total
		// pageNum: data.pageNum,
		// pageSize: data.pageSize
	};
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	let newParams = JSON.parse(JSON.stringify(params));
	// newParams.username && (newParams.username = "custom-" + newParams.username);
	return listClient(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const status = reactive([
	{
		userLabel: "启用",
		userStatus: 1
	},
	{
		userLabel: "禁用",
		userStatus: -1
	}
]);
// 表格配置项
const columns: ColumnProps[] = [
	// { type: "selection", fixed: "left", width: 80 },
	{ type: "index", label: "#", width: 80, fixed: "left" },
	// { type: "expand", label: "Expand", width: 100 },
	{
		width: 160,
		prop: "username",
		label: "客户名称",
		search: { el: "input" },
		fixed: "left"
	},
	// 多级 prop
	{ prop: "user_mark", label: "客户唛头", width: 160 },
	{ prop: "code", label: "客户代码", search: { el: "input" }, width: 160 },
	{
		width: 160,
		prop: "mobile",
		label: "电话",
		render: (scope: { row: any }) => {
			return (
				<>
					+{scope.row.area_code} {scope.row.mobile}
				</>
			);
		}
	},
	{ prop: "desc", label: "客户备注", width: 300 },
	{ prop: "number_orders", label: "累积下单数量", width: 160 },
	{
		width: 160,
		prop: "status",
		label: "用户状态",
		enum: status,
		search: { el: "tree-select", props: { filterable: true } },
		fieldNames: { label: "userLabel", value: "userStatus" },
		render: (scope: { row: any }) => {
			return (
				<>
					<el-tag type={scope.row.status == 1 ? "success" : "danger"}>{scope.row.status == 1 ? "启用" : "禁用"}</el-tag>
				</>
			);
		}
	},
	{
		prop: "add_time",
		label: "创建时间",
		width: 180,
		search: {
			el: "date-picker",
			span: 1,
			props: {
				type: "datetimerange",
				valueFormat: "YYYY-MM-DD HH:mm:ss",
				defaultTime: [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
			}
		}
	},
	{ prop: "operation", label: "操作", fixed: "right", width: 220 }
];

// 删除用户信息
const deleteAccount = async (params: any) => {
	await useHandleData(delClient, { client_id: params.id }, `删除【${params.username}】用户`);
	proTable.value.getTableList();
};

// 导出用户列表
// const downloadFile = async () => {
// 	ElMessageBox.confirm("确认导出用户数据?", "温馨提示", { type: "warning" }).then(() =>
// 		useDownload(exportUserInfo, "用户列表", proTable.value.searchParam)
// 	);
// };

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref();
const openDrawer = (title: string, rowData: any = {}) => {
	let params = {
		title,
		rowData: {
			client_id: rowData.id,
			username: rowData.username,
			status: rowData.status,
			user_mark: rowData.user_mark,
			code: rowData.code,
			area_code: rowData.area_code,
			mobile: rowData.mobile,
			desc: rowData.desc
		},
		isView: title === "查看",
		api: title === "新增" ? createClient : title === "编辑" ? setClient : "",
		getTableList: proTable.value.getTableList
	};
	drawerRef.value.acceptParams(params);
};
const showDialog = ref(false);
const client_id = ref();
const openDialog = (params: number) => {
	showDialog.value = true;
	client_id.value = params;
};
</script>
